<template>
  <div class="app-container">
    <el-form>
      <div class="params head-form">
        <el-form-item label="支付账号">
          <el-input v-model="params.account" style="flex: 1" placeholder="请输入" @blur="init" @keyup.enter="init" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="params.status" style="flex: 1" @change="init">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入关键词" v-model="params.partnerName" style="flex: 1" @blur="init" @keyup.enter="init">
            <template #prepend>
              <el-select v-model="params.partnerType" placeholder="请选择" style="width: 115px" @change="init">
                <el-option v-for="(item, index) in type" :label="item" :value="Number(index)" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button :icon="RefreshRight" plain type="primary" @click="reset">重置</el-button>
          <el-button :icon="Plus" type="primary" @click="openModal"> 新建 </el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="table-container">
      <div class="table-head">
        <div>支付方式</div>
        <div>支付账号</div>
        <div>支付对象类型</div>
        <div>户名</div>
        <div>支付对象</div>
        <div>禁用/启用</div>
        <div>添加时间</div>
        <div>操作</div>
      </div>
      <div class="loading" v-if="loading" v-loading="loading"></div>
      <el-empty v-if="!data.length && !loading" />
      <el-scrollbar max-height="calc(100vh - 320px)">
        <div class="table-content">
          <div v-for="item in data">
            <div>{{ item.dictName }}</div>
            <div>{{ item.account }}</div>
            <div>{{ type[item.type] }}</div>
            <div>{{ item.accountName }}</div>
            <div>{{ item.name }}（{{ item.partnerId }}）</div>
            <div>
              <el-tag>{{ item.status ? "启用" : "禁用" }}</el-tag>
            </div>
            <div>{{ item.createTime }}</div>
            <div><el-button type="primary" link @click="openModal(item)">编辑</el-button></div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="pagination">
      <el-pagination
        v-model:current-page="query.current"
        v-model:page-size="query.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="init"
        @current-change="init"
      />
    </div>
    <el-dialog v-model="visible" width="500" center align-center show-close @close="resetModal">
      <template #title>
        <custom-title :title="(isNew ? '添加' : '编辑') + '其他合作方'" />
      </template>
      <el-form :model="form" ref="formRef" label-width="auto" :rules="rules">
        <el-form-item label="合作方" prop="partnerId">
          <el-select-v2
            v-model:model-value="form.partnerId"
            filterable
            remote
            :remote-method="remoteMethod"
            clearable
            :options="options"
            :props="props"
            placeholder="请输入名称"
          />
        </el-form-item>
        <el-form-item label="支付方式" prop="dictId">
          <el-select v-model="form.dictId" placeholder="请选择">
            <el-option v-for="item in payTypeList" :value="item.dictId" :key="item.dictId" :label="item.dictName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" />
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-input v-model="form.bankName" />
        </el-form-item>
        <el-form-item label="户名" prop="accountName">
          <el-input v-model="form.accountName" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" style="--el-switch-on-color: #007dff" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="comfirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { RefreshRight, Plus } from "@element-plus/icons-vue";
import { getList, add, edit } from "@/apis/account";
import { getList as getCollaboratorsList } from "@/apis/collaborators";
import { payTypeDict } from "@/apis/dict/dict";
import { ElMessage } from "element-plus";
import { type } from "@/utils/config";

const query = ref({
  current: 1,
  size: 10
});
const props = {
  label: "name",
  value: "partnerId"
};

const collaboratorsQuery = ref({
  current: 1,
  size: 10
});
const options = ref([]);
const payTypeList = ref([]);
const loading = ref(false);
const params = ref({
  name: undefined,
  status: undefined
});
const form = ref({
  status: 1
});
const resetModal = () => {
  form.value = { status: 1 };
  formRef.value.resetFields();
};
const mergeId = tree => {
  tree.forEach(item => {
    if (item.children && item.children.length) {
      mergeId(item.children);
    } else {
      item.name = item.name + "(" + item.partnerId + ")";
    }
  });
  return tree;
};
const remoteMethod = async query => {
  if (query !== "") {
    const {
      data: { list = [] }
    } = await getCollaboratorsList(collaboratorsQuery.value, { name: query, status: 1 });
    options.value = mergeId(list);
  } else {
    options.value = [];
  }
};

const isNew = ref(true);
const formRef = ref(null);
const visible = ref(false);
const data = ref([]);
const total = ref(0);
const init = async () => {
  const { data: { list = [], total: totalNum } = {} } = await getList(query.value, params.value);
  data.value = list;
  total.value = totalNum;
  loading.value = false;
};
const mobileVerify = (rule, value, callback) => {
  const regex = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
  if (regex.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确的手机号"));
  }
};
const rules = {
  partnerId: [{ required: true, message: "请选择合作方", trigger: "blur" }],
  dictId: [{ required: true, message: "请选择支付方式", trigger: "blur" }],
  contacts: [{ validator: mobileVerify, trigger: "blur" }],
  account: [
    { required: true, message: "请输入账户", trigger: "blur" },
    { max: 20, message: "账号不能超过20个字符" }
  ],
  bankName: [{ max: 20, message: "开户银行不能超过20个字符" }],
  accountName: [{ max: 20, message: "户名不能超过20个字符" }],
  remark: [{ max: 100, message: "备注不能超过100个字符" }]
};
const reset = () => {
  data.value = [];
  loading.value = true;
  params.value = {};
  init();
};
const openModal = item => {
  if (item.partnerId) {
    isNew.value = false;
    form.value = { ...item };
    options.value = [{ partnerId: item.partnerId, name: item.name }];
  } else {
    isNew.value = true;
  }
  visible.value = true;
};
const comfirm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return;
    if (isNew.value) {
      try {
        await add(form.value);
        visible.value = false;
        ElMessage.success("编辑成功");
        init();
      } catch (error) {}
    } else {
      try {
        await edit(form.value);
        visible.value = false;
        ElMessage.success("编辑成功");
        init();
      } catch (error) {}
    }
  });
};
const getPayTypeList = async () => {
  const { data = [] } = await payTypeDict({ status: 1 });
  payTypeList.value = data;
};
onMounted(() => {
  loading.value = true;
  getPayTypeList();
  init();
});
</script>

<style lang="scss" scoped>
$border: 1px solid #dcdfe6;

.loading {
  height: 300px;
}

.params {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  column-gap: 30px;
}

.table-container {
  border: $border;
  line-height: 50px;
  text-align: center;

  @mixin col {
    min-height: 50px;
    display: grid;
    grid-template-columns: repeat(4, 1fr) 2fr repeat(3, 1fr);

    > :last-child {
      border-left: $border;
    }
  }

  .table-head {
    @include col;
    background: #f2f6fc;
    color: #909399;
    border-bottom: $border;
  }

  .table-content {
    > div {
      height: auto;
      @include col;
      border-bottom: $border;
      color: #4e5969;

      > div {
        display: flex;
        justify-content: center;
        align-items: center;
        word-break: break-all;
      }
    }

    :last-child {
      border: none;
    }

    > div:nth-child(even) {
      background: #f5f7fa;
    }
  }

  .link {
    color: #007dff;
    text-decoration: underline;
    cursor: pointer;
  }

  .el-button.is-link {
    color: #007dff;
  }
}
</style>
